/**
 * @Title:RoleAction.java
 * CopyRight(c)2010-DMX
 */
package com.dmx.fw.web.struts2.action.system;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletResponse;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.struts2.ServletActionContext;
import org.springframework.security.web.access.intercept.DefaultFilterInvocationSecurityMetadataSource;
import org.springframework.security.web.access.intercept.FilterSecurityInterceptor;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import com.dmx.fw.bean.mapping.pojo.Resc;
import com.dmx.fw.bean.mapping.pojo.Role;
import com.dmx.fw.constant.ViewConstant;
import com.dmx.fw.service.interfaces.RoleService;
import com.dmx.fw.web.struts2.action.BaseAction;
/**
 * @Description: Role Manager
 * @author Ma Qiang
 * @date 2010-4-29
 * @version V1.0
 */
public class RoleAction extends BaseAction {
	final private static Log log = LogFactory.getLog(RoleAction.class);
	private final static String INTERCEPTOR_BEAN ="filterInvocationInterceptor";
	private final static String METADATA_BEAN ="tempSecurityMetadataSource";
	/**
	 * @Fields id : 角色ID
	 */
	private String id;
	/**
	 * @Fields checkedFunc : 已经选择的所有功能权限，字符串，从dhtmlTree中或得处理后传过来。
	 */
	private String checkedFunc;
	/**
	 * @Fields checkedList : 角色已选择的功能权限，List从数据库取得。
	 */
	private List checkedList = new ArrayList();
	/**
	 * @Fields role : 角色对象
	 */
	private Role role = new Role();
	/**
	 * @Fields oldName : 旧名称，修改角色时用到，角色名称不能重复
	 */
	private String oldName;
	/**
	 * @Fields roleService : RoleService
	 */
	private RoleService roleService;

	public String execute() throws Exception {
		return super.execute();
	}
	/**
	 * @Description: 进入添加输入界面
	 * @param 
	 * @return String
	 */
	public String doAddInput() {
		return "addInput";
	}
	/**
	 * @Description: 执行添加提交操作
	 * @param 
	 * @return String
	 */
	public String doAddSubmit() throws Exception {
		 String[] funcArray = null;
		 //分解选择的功能权限字符串，转化成数组
		 if (checkedFunc != null && !checkedFunc.equals("")) {
			 checkedFunc=checkedFunc+",10";
			 funcArray = checkedFunc.split(",");
		 }
		 role.setName("ROLE_"+role.getName());
		 //检查管理区域下的角色名是否重复
		 if (roleService.checkRoleNameUnique(role)) {
			 this.setErrorInfo(this.getText("role.roleNameDuplicate"));
			 //this.setAjaxJsonMsgResult(getText("role.roleNameDuplicate"),null);
			 return "addInput";
		 } else {
			 roleService.save(role, funcArray);
			 updateStringSecurityMetadata();
			 this.setSuccessinfo(this.getText("info.addSuccess"));
			 //this.setAjaxJsonUrlResult("system/roleSearch.action?act=reQuery&busiId=searchRole");
			 return "list";
		 }
	}
	/**
	 * @Description: 进入修改输入界面
	 * @param 
	 * @return String
	 */
	public String doEditInput() {
		role = roleService.getRole(Long.valueOf(id));
		return "addInput";
	}
	/**
	 * @Description: 执行修改提交界面
	 * @param 
	 * @return String
	 */
	public String doEditSubmit() throws IOException {
		String[] funcArray = null;
		//分解选择的功能权限字符串，转化成数组
		if (checkedFunc != null && !checkedFunc.equals("")) {
			checkedFunc=checkedFunc+",10";
			funcArray = checkedFunc.split(",");
		}
		//检查管理区域下的角色名是否重复
		role.setName("ROLE_"+role.getName());
		if (!oldName.equalsIgnoreCase(role.getName())&& roleService.checkRoleNameUnique(role)) {
			//this.setAjaxJsonMsgResult(getText("role.roleNameDuplicate"),null);
			 this.setErrorInfo(this.getText("role.roleNameDuplicate"));
			 this.id=""+role.getId();
			 return doEditInput();
		} else {
			roleService.update(role, funcArray);
			updateStringSecurityMetadata();
			this.setSuccessinfo(this.getText("info.modifySuccess"));
			return "list";
			//this.setAjaxJsonUrlResult("system/roleSearch.action?act=reQuery&busiId=searchRole");
		}
	}
	/**
	 * @Description: 执行删除操作
	 * @param 
	 * @return String
	 */
	public String doDelete() throws IOException {
		 List temp = roleService.findOperatorByRoleId(new Long(id));
		 //检查角色是否被引用
		 if (temp != null && !temp.isEmpty()) {
			 this.setErrorInfo(getText("role.roleIsUsed"));
		 } else {
			 role.setId(new Long(id));
			 roleService.delete(role);
			 this.setSuccessinfo(this.getText("info.deleteSuccess"));
			 updateStringSecurityMetadata();
		 }
		 //this.setAjaxJsonUrlResult("system/roleSearch.action?act=reQuery&busiId=searchRole");
		 return "list";
	}
	/**
	 * @Description: 执行查看动作
	 * @param 
	 * @return String
	 */
	public String doView() {
		role = roleService.getRole(Long.valueOf(id));
		return "addInput";
	}
	/**
	 * @Description: 加载功能权限树
	 * @param 
	 * @return String
	 * @exception Exception
	 */
	public String loadResc() throws Exception {
		//默认根为0
		String parentId = "0";

		String outInfo = "";
		List tempList = new ArrayList();
		//判断是否超级管理员，是-列出所有功能权限
/*		boolean isView = false;
		if (pageState.equals(ViewConstant.VIEWSTATUS)) {
			isView = true;
		}
		if (isView) {
			tempList = roleService.findRescByRole(role.getId());
		} else if (getCurrOperator().getOperatorType() != null
				&& getCurrOperator().getOperatorType().equals("superadmin")) {
			tempList = roleService.findAllResc();
		} else {
			tempList = roleService.findAllRescByOperator(getCurrOperator().getId());
		}*/
		
		tempList = roleService.findAllResc();
		
		//生成xml字符串
		outInfo = createXmlAll(parentId, tempList, null);
		HttpServletResponse res = ServletActionContext.getResponse();
		res.setContentType("text/xml;charset=UTF-8");
		res.setHeader("Cache-Control", "no-store");
		res.setHeader("Pragma", "no-cache");
		res.setDateHeader("Expires", 0);
		PrintWriter out = res.getWriter();
		out.print(outInfo);
		out.flush();
		out.close();
		return null;
	}

	private String createXmlAll(String parentId, List tempList, String type) {
		StringBuffer outXml = new StringBuffer(
				"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n");
		outXml.append("<tree id=\"");
		outXml.append(parentId);
		outXml.append("\">\n");
		String itemString;
		//如果为修改，选中已选项目
		if (pageState.equals(ViewConstant.EDITSTATUS)
				|| pageState.equals(ViewConstant.VIEWSTATUS)) {
			checkedList = roleService.findRescByRoleId(role.getId());
		}
		itemString = createItem(parentId, tempList);
		outXml.append(itemString);
		outXml.append("</tree>\n");
		return outXml.toString();
	}
	/**
	 * @Description: 生成树的所有item
	 * @param parentId
	 * @param tempList
	 * @return String
	 */
	private String createItem(String parentId, List tempList) {
		StringBuffer temp = new StringBuffer();
		List subList = new ArrayList();
		//查询所有parentId下的子项目，生成subList
		for (int i = 0; i < tempList.size(); i++) {
			List function = (List) tempList.get(i);
			String s = (String) function.get(1);
			String name = (String) function.get(2);
			if (s.equals(parentId)) {
				subList.add(function);
				//如果数据库中parentId为空，则添加到根0下。
			}
			if (s == null || s.equals("") || s.equalsIgnoreCase("null")|| s.equals(0)) {
				function.set(1, parentId);
				tempList.set(i, function);
				subList.add(function);
				//tempList.remove(function);
			}
		}
		//递归生成树string
		if (!subList.isEmpty()) {
			for (int i = 0; i < subList.size(); i++) {
				List function = (List) subList.get(i);
				temp.append("<item text=\"");
				temp.append(this.getText(function.get(2).toString()));
				temp.append("\" id=\"");
				temp.append(function.get(0));
				temp.append("\" open=\"1\" ");
				temp.append(" im0=\"icon_1s.gif\" im1=\"icon_1s.gif\" im2=\"icon_1s.gif\"");
				for (int j = 0; j < checkedList.size(); j++) {
					Resc checkedResc = (Resc) checkedList.get(j);
					String funcId = (String) function.get(0);
					if(checkedResc.getId()!=10&&!"".equals(checkedResc.getResString())){
						if (funcId.equals(String.valueOf(checkedResc.getId()))) {
							temp.append(" checked=\"0\"");
						}
					}
				}

				temp.append(" child=\"1\">");
				temp.append(createItem(String.valueOf(function.get(0)),
						tempList));
				temp.append("</item>\n");
			}
		}
		return temp.toString();
	}
	/**
	 * @Description: 动态生成树时用此方法
	 * @param parentId
	 * @param tmpList
	 * @return String
	 */
	private String createXml(String parentId, List tmpList) {
		StringBuffer outXml = new StringBuffer(
				"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n");
		outXml.append("<tree id=\"");
		outXml.append(parentId);
		outXml.append("\">\n");
		for (int i = 0; i < tmpList.size(); i++) {
			Resc resc = (Resc) tmpList.get(i);
			outXml.append("<item text=\"");
			outXml.append(resc.getName());
			outXml.append("\" id=\"");
			outXml.append(resc.getId());
			outXml
					.append("\" im0=\"book.gif\" im1=\"books_open.gif\" im2=\"book.gif\"");

			outXml.append(" child=\"1\"");

			outXml.append("></item>\n");
		}
		outXml.append("</tree>\n");
		return outXml.toString();
	}
	
	
	private void updateStringSecurityMetadata(){
		WebApplicationContext  wac = WebApplicationContextUtils.getWebApplicationContext(ServletActionContext.getServletContext());
		DefaultFilterInvocationSecurityMetadataSource metadata= (DefaultFilterInvocationSecurityMetadataSource)wac.getBean(METADATA_BEAN);
		FilterSecurityInterceptor interceptor= (FilterSecurityInterceptor)wac.getBean(INTERCEPTOR_BEAN);
		interceptor.setSecurityMetadataSource(metadata);
	}
	/**
	 * @return the role
	 */
	public Role getRole() {
		return role;
	}

	/**
	 * @param role
	 *            the role to set
	 */
	public void setRole(Role role) {
		this.role = role;
	}

	/**
	 * @return the roleService
	 */
	public RoleService getRoleService() {
		return roleService;
	}

	/**
	 * @param roleService
	 *            the roleService to set
	 */
	public void setRoleService(RoleService roleService) {
		this.roleService = roleService;
	}
	/**
	 * @return the id
	 */
	public String getId() {
		return id;
	}

	/**
	 * @param id
	 *            the id to set
	 */
	public void setId(String id) {
		this.id = id;
	}

	/**
	 * @return the checkedFunc
	 */
	public String getCheckedFunc() {
		return checkedFunc;
	}

	/**
	 * @param checkedFunc
	 *            the checkedFunc to set
	 */
	public void setCheckedFunc(String checkedFunc) {
		this.checkedFunc = checkedFunc;
	}

	/**
	 * @return the checkedList
	 */
	public List getCheckedList() {
		return checkedList;
	}

	/**
	 * @param checkedList
	 *            the checkedList to set
	 */
	public void setCheckedList(List checkedList) {
		this.checkedList = checkedList;
	}

	/**
	 * @return the oldName
	 */
	public String getOldName() {
		return oldName;
	}

	/**
	 * @param oldName
	 *            the oldName to set
	 */
	public void setOldName(String oldName) {
		this.oldName = oldName;
	}
}
